package com.stox.charting.ui.swing.event.listener;

import java.awt.Rectangle;
import java.util.List;

import com.stox.charting.ui.swing.event.ChartModelChangedEvent;
import com.stox.charting.ui.swing.model.ChartModel;
import com.stox.charting.ui.swing.model.ChartModel.ChartModelListener;
import com.stox.charting.ui.swing.model.Viewport;
import com.stox.charting.ui.swing.model.uiUnit.AbstractUiUnit;
import com.stox.charting.ui.swing.model.uiUnit.UiUnit;
import com.stox.charting.ui.swing.scheme.color.ColorScheme;

public class UiUnitsChangedEventListener<T> implements ChartModelListener {

	@SuppressWarnings("unchecked")
	@Override
	public void chartModelChanged(ChartModelChangedEvent event) {
		if(event.getProperty().equalsIgnoreCase("uiUnits")){
			ChartModel<T> chartModel = (ChartModel<T>)event.getSource();
			chartModel.fireChartModelChangedEvent("viewport");
			
			Viewport<?> viewport = chartModel.getViewport();
			Rectangle r = chartModel.getChart().getVisibleRect();
			double width = r.getWidth()/(viewport.getStartIndex() - viewport.getEndIndex());
			double factor = r.getHeight()/(viewport.getMaximumValueVisible()-viewport.getMinimumValueVisible());
			List<? extends UiUnit> uiUnits = viewport.getUiUnits();
			if(uiUnits != null && !uiUnits.isEmpty()){
				for(int i = viewport.getEndIndex(); i < viewport.getStartIndex(); i++){
					AbstractUiUnit<T> abstractUiUnit = (AbstractUiUnit<T>)uiUnits.get(i);
					abstractUiUnit.processUi(width,factor);
					ColorScheme<T> colorScheme = chartModel.getColorScheme();
					if(colorScheme != null){
						abstractUiUnit.setColor(colorScheme.getColor(chartModel, i));
					}
				}
			}
		}
	}
}
